<?php

class Acl_Controller extends Public_Controller
{
    /**
     * 群组列表
     */
    public function group_indexAction()
    {
        //获取群组权限设置
        $groups = acl::getList('acl_groups');
        $this->view->set(array(
            'res' => $groups,
        ));
        $this->view->display();
    }

    /**
     * 群组权限配置
     */
    public function group_configAction()
    {
        //组件名称
        $name = $this->get('component','root');

        //读取已经激活的组件
        $components = Component::$active;

        //更新权限仓库表
        if ($post = $this->post())
        {
            $acl_assets = $this->model('acl_assets');
            $asset_name = $post['name'];

            $list = array();
            //过滤掉空值
            foreach ($post[$asset_name] as $key => $value)
            {
                foreach($value as $k => $v)
                {
                    if($v == '1' || $v == '0')
                        $list[$key][$k] = $v;
                }
            }
            unset($post);
            $list = json_encode($list);

            if (!$acl_assets->getOne('name=?', $asset_name))
            {
                $insert = array(
                    'name' => $asset_name, 'rules' => $list, 'parent_id' => 0, 'level' => 0, 'title' => $components[$asset_name],
                );
                $acl_assets->insert($insert);
                //更新左右值
                acl::rebuild('acl_assets');
            } 
            else
            {
                $acl_assets->update(array('rules' => $list), '`name`=?', $asset_name);
            }
            $this->redirect($this->view->_data['base_url'].'user/acl/group_config/component/'.$asset_name);
        }

        //生成激活组件权限设置选择菜单
        $components = html::select($components, array('name'=>'component'), $name);

        $groups = join("\n", acl::generate($name, $name));
        $this->view->set(array(
            'name' => $name,
            'res' => $groups,
            'components' => $components,
        ));
        $this->view->display();
    }

    /**
     * 群组添加和修改
     */
    public function group_addAction()
    {
        $id = (int) $this->get('id');

        //模型初始化
        $model = $this->model('acl_groups');

        //当前角色信息
        $result = $model->find($id);

        //插入新数据和更新表
        if($post = $this->post())
        {
            if($post['id'] > 0)
                $model->update($post, 'id=?', $post['id']);
            else
                $model->insert($post);

            //更新左右值
            acl::rebuild('acl_groups');

            $this->alert('资源数据更新成功', $this->view->_data['base_url'].'user/acl/group_index');
        }
        
        $html_groups = null;
        if ($result['parent_id'] > 0 || empty($result))
        {
            // 群组所有列表
            $_groups = acl::getList('acl_groups');
            if (is_array($_groups))
            {
                $groups  = array();
                foreach ($_groups as $value)
                {
                    $groups[$value['id']] = str_repeat('|&ndash; ',  $value['level']).$value['title'].' ['.$value['description'].']';
                }
                $html_groups = html::select($groups, array('name'=>'parent_id'), $result['parent_id']);
            }
        }

        $this->view->set(array(
            'result' => $result,
            'html_groups' => $html_groups,
        ));

        $this->view->display();
    }

    /**
     * 删除群组
     */
    public function group_deleteAction()
    {
        $id = (int)$this->get('id');

        //模型实例
        $model = $this->model('acl_groups');

        //获取要删除的子节点
        $data = $model->getOne('parent_id=?', $id);

        //检查自己下面是否有数据
        if(is_array($data))
        {
            $this->alert('对不起，不能删除有子群组的数据！', -1);
        } else {
            $model->delete('id=?', $id);
            //更新左右值
            acl::rebuild('acl_groups');
        }
        $this->alert('恭喜你，组数据删除成功', $this->view->_data['base_url'].'user/acl/group_index');
    }

    /**
     * 账户列表
     */
    public function user_indexAction()
    {
        $page_id = (int) $this->get('page', 1);

        //模型实例
        $model = $this->model('users');

        //获取所有用户组
        $sql = 'SELECT m.user_id, g.* FROM #__acl_groups as g LEFT JOIN #__acl_user_group_map AS m ON g.id = m.group_id ORDER BY g.lft ASC';
        $_groups = Work::instance('Model')->execute($sql);

        $groups = array();
        if (is_array($_groups))
        {
            foreach($_groups as $v)
            {
                $user_id = $v['user_id'];
                isset($groups[$user_id]) ? $groups[$user_id] .= ','.$v['description'] : $groups[$user_id] = $v['description'];
            }
        }

        //读取配置文件
        $site = Work::config()->load('site');

        // 获取主数据
        $result = $model->from('users')->order('id DESC')->page_limit($page_id, $site['page_sum'])->select();

        // 统计数据库总条数
        $total = $model->count('users', 'id');

        $pager = new pager();
        $pager->conf($total, $page_id, url::action().'?page', $site['page_sum'], $site['page_few']);
        $pagelist = $pager->getlink();

        //获取群组权限设置
        $this->view->set(array(
            'groups' => $groups,
            'result' => $result,
            'pagelink' => $pagelist,
        ));
        $this->view->display();
    }

    /**
     * 群组添加和修改
     */
    public function user_addAction()
    {
        $id = (int) $this->get('id');

        //模型实例
        $model = $this->model('users');

        //插入新数据和更新表
        if($post = $this->post())
        {
            if (empty($post['id']))
            {
                // 写入新数据
                $post['created'] = date('Y-m-d H:i:s');
                $model->insert($post);
                $user_id = $model->get_insert_id();
            }
            elseif ($post['id'] > 0)
            {
                // 更新数据
                $model->update($post, 'id=?', $post['id']);
                $user_id = $post['id'];
            }

            //写入群组
            if($user_id > 0)
            {
                $user_group_model = $this->model('acl_user_group_map');

                //删除旧记录
                $user_group_model->delete('user_id=?', $user_id);

                //循环写入新纪录
                if(!empty($post['group_id']))
                {
                    foreach($post['group_id'] as $v)
                    {
                        $insert = array('group_id' => $v, 'user_id' => $user_id);
                        $user_group_model->insert($insert);
                    }
                }
            }
            $this->alert('资源数据更新成功', $this->view->_data['base_url'].'user/acl/user_index');
        }

        //获取当前用户组编号
        $_group_ids = ($id > 0) ? $model->from('acl_user_group_map', 'group_id')->where('user_id=?', $id)->select() : array();

        $group_ids = array();
        if (is_array($_group_ids))
        {
            foreach ($_group_ids as $v)
            {
                $group_ids[] = $v['group_id'];
            }
        }

        //当前用户信息
        $result = $model->find($id);

        $groups = acl::getList('acl_groups');

        $this->view->set(array(
            'group_ids' => $group_ids,
            'result' => $result,
            'groups' => $groups,
        ));
        $this->view->display();
    }

}
